import React from 'react';
import { Table, Button, Modal, Input, message, Pagination, Select, Checkbox, TreeSelect } from 'antd';
import './goodsrelevance.less';
import $ from 'jquery';
import Config from '../../common/config';

const config = new Config();
const InputGroup = Input.Group;
const Option = Select.Option;
const token = sessionStorage.getItem('token')

export default class FloorProduct extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            relationid: this.props.relationid,//关联ID
            productid: "0",//商品ID
            productlist: [],//全部商品列表
            productcount: 1,//全部商品条数
            pagesize: 8,// 每页显示的页数
            pageindex: 1,// 当前页
            keyWord: '',//关键字
            categoryid: undefined,//分类   
            categoryData: [], //所有分类  
            checkedProducts: [], //选择的商品
            isdrugstatus: undefined,//类别
            iscoldstorage: undefined,//冷藏
            isspecialdrug: undefined,//特管
        }
    }
    componentDidMount() {
        this.getProductList();
        this.getCategory();
    }
    //没有存在于关联表中的商品列表
    getProductList() {
        $.ajax({
            url: `${config.JuseProduct}/relations/productList`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                inKey: this.state.keyWord,//关键字
                categoryCode: this.state.categoryid,//分类
                isPres: this.state.isdrugstatus,
                isRefrig: this.state.iscoldstorage,
                isEphe: this.state.isspecialdrug,
            },
            success: res => {
                console.log("未关联商品列表", res);
                if (res.code === 200) {
                    res.data.rows.forEach((item, index) => {
                        item.index = index + 1
                    })
                    this.setState({
                        productlist: res.data.rows,
                        productcount: res.data.count,
                    });
                }
            }
        });
    }
    //分类列表
    getCategory() {
        $.ajax({
            url: `${config.JuseProduct}/categories/getCategoriesTree`,
            type: "get",
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('分类列表', res);
                if (res.code === 200) {
                    const data = res.data;
                    const loop = list => {
                        list.forEach(item => {
                            item.key = item.categoryCode
                            item.value = item.categoryCode
                            item.label = item.categoryRename || item.categoryName
                            if (item.son) {
                                item.children = item.son
                                loop(item.children)
                            }
                        })
                    }
                    loop(res.data)
                    this.setState({
                        categoryData: res.data
                    })
                }
            }
        });
    }
    //输入搜索关键字
    changeKeyword(e) {
        if (e.target.value.length > 32) {
            message.error('搜索关键字长度为1-32', 2);
        } else {
            this.setState({
                keyWord: e.target.value
            })
        }
    }
    //选择分类
    changeCategory(value) {
        this.setState({
            categoryid: value
        })
    }
    //类别的改变事件
    drugStatusChange(v) {
        this.setState({
            isdrugstatus: v
        });
    }
    //冷藏的改变事件
    coldstorageChange(v) {
        this.setState({
            iscoldstorage: v
        });
    }
    //特管的改变事件
    specialdrugChange(v) {
        this.setState({
            isspecialdrug: v
        });
    }
    //搜索
    searchProduct() {
        this.setState({
            pageindex: 1
        }, () => this.getProductList())
    }
    //重置
    clearSearch() {
        this.setState({
            keyWord: "",
            categoryid: undefined,
            isdrugstatus: undefined,
            iscoldstorage: undefined,
            isspecialdrug: undefined,
            pageindex: 1
        }, () => {
            this.getProductList()
        })
    }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.getProductList();
        });
    }
    //选择商品
    selectProduct(text, record, e) {
        const { products } = this.props;
        let { checkedProducts } = this.state;
        if (e.target.checked) {
            checkedProducts.push(record);
        } else {
            checkedProducts.forEach((item, i) => {
                if (item.productId == text) {
                    checkedProducts.splice(i, 1);
                }
            });
        }
        //console.log('选择', checkedProducts)
        this.setState({
            checkedProducts
        })
    }
    //确认添加
    handleOK() {
        let { checkedProducts } = this.state;
        const { addProduct, products } = this.props;
        if (addProduct) {
            addProduct(checkedProducts);
            this.setState({
                checkedProducts: [],
            });
        }
    }
    //取消
    handleCancel() {
        const { cancelProduct } = this.props;
        if (cancelProduct) {
            cancelProduct();
            this.setState({
                checkedProducts: [],
            });
        }
    }
    //关闭对话框后重置状态
    resetModal() {
        this.setState({
            pageindex: 1,
            keyWord: '',
            categoryid: undefined,
            isdrugstatus: undefined,
            iscoldstorage: undefined,
            isspecialdrug: undefined,
        }, () => this.getProductList())
    }
    render() {
        // let checkedProductId = [];
        let checkedProductId = this.state.productid == "0" ? "" : this.state.productid;
        {
            this.state.checkedProducts.forEach((val, i) => {
                if (val) {
                    if (checkedProductId == "") {
                        checkedProductId += val.productid;
                    } else {
                        checkedProductId += "," + val.productid;
                    }
                }
            });
        }
        const columns = [{
            title: '勾选',
            dataIndex: '',
            width: '5%',
            render: (text, record) => {
                let checked = false
                this.state.checkedProducts.forEach(item => {
                    if (item.productId === record.productId) {
                        checked = true
                    }
                })
                let disabled = false
                if (!checked && this.state.checkedProducts.length >= 10) {
                    disabled = true
                }
                return <Checkbox
                    onChange={this.selectProduct.bind(this, record.productId, record)}
                    checked={checked}
                    disabled={disabled}
                ></Checkbox>
            }
        }
            , {
            title: '序号',
            dataIndex: 'index',
        }
            , {
            title: '商品ID',
            dataIndex: 'productId',
        }, {
            title: '商品信息',
            dataIndex: '',
            render: (text, record) => {
                return <div>
                    药品名称：{record.productName}&nbsp;&nbsp;规格：{record.specification}&nbsp;&nbsp;通用名称：{record.generalName}&nbsp;&nbsp;品牌：{record.brandName}
                </div>
            },
            width: 300
        }, {
            title: '商品图片',
            dataIndex: '',
            render: (text, record) => {
                return <img src={record.imageUrl + record.listImage} style={{ width: "40px" }} />
            },
            width: 100
        }, {
            title: '商品价格',
            dataIndex: '',
            render: (text, record) => {
                return <div>零售价：{record.retailp}&nbsp;&nbsp;商城价：{record.marketPrice}</div>
            },
            width: 100
        }, {
            title: '标签',
            dataIndex: 'tagList',
            render: (text, record) => {
                return <div>{text.map(item => item.tagName).join(',')}</div>
            },
        }];

        return (
            <Modal
                className="floor-pmodal"
                title="已上架商品列表" tle="已上架商品列表"
                visible={this.props.visible}
                okText={"确认添加"}
                className='pangqian-relationtoy'
                onOk={() => this.handleOK()}
                onCancel={() => this.handleCancel()}
                maskClosable={false}
                afterClose={() => this.resetModal()}
            >
                <div className='member-content-Search clearfix'>
                    <div className='addetd addetd-b'>
                        <Input className='addetd-a-r' addonBefore="内码/药品名称/通用名/品牌" placeholder="请输入" value={this.state.keyWord} onChange={(e) => this.changeKeyword(e)} />
                    </div>
                    <div className='addetd addetd-bb'>
                        <InputGroup compact>
                            <Input addonBefore="分 类" />
                            <TreeSelect
                                style={{ width: 210 }}
                                value={this.state.categoryid}
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                treeData={this.state.categoryData}
                                placeholder="请选择"
                                // treeDefaultExpandAll
                                onChange={(value) => this.changeCategory(value)}
                            />
                        </InputGroup>
                    </div>
                    <div className='member-content-Search clearfix'>
                        <div className='addetd addetd-a'>
                            <InputGroup compact>
                                <Input addonBefore="类 别" />
                                <Select value={this.state.isdrugstatus} onChange={this.drugStatusChange.bind(this)} placeholder='请选择'>
                                    <Option value="Y">处方药</Option>
                                    <Option value="N">非处方药</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <div className='addetd addetd-a'>
                            <InputGroup compact>
                                <Input addonBefore="冷 藏" />
                                <Select value={this.state.iscoldstorage} onChange={this.coldstorageChange.bind(this)} placeholder='请选择'>
                                    <Option value="Y">冷藏</Option>
                                    <Option value="N">非冷藏</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <div className='addetd addetd-a'>
                            <InputGroup compact>
                                <Input addonBefore="特 管" />
                                <Select value={this.state.isspecialdrug} onChange={this.specialdrugChange.bind(this)} placeholder='请选择'>
                                    <Option value="Y">特管药品</Option>
                                    <Option value="N">非特管药品</Option>
                                </Select>
                            </InputGroup>
                        </div>
                        <Button type="primary" className='member-button' icon="search" onClick={this.searchProduct.bind(this)}>搜索</Button>
                        <Button type="primary" className='member-button' icon="reload" onClick={this.clearSearch.bind(this)}>重置</Button>
                    </div>
                </div>
                <div className='allgoods-table clearfix '>
                    <Table
                        rowKey='productId'
                        columns={columns}
                        dataSource={this.state.productlist}
                        pagination={false}
                        bordered
                    />
                </div>
                <div className="floor-ppagi">
                    {
                        this.state.productcount == 0 ?
                            <p className="floor-ppagip">
                                共{this.state.productcount}条记录
                        </p> :
                            <p className="floor-ppagip">
                                当前显示
                            {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                            {this.state.pagesize * this.state.pageindex < this.state.productcount ? this.state.pagesize * this.state.pageindex : this.state.productcount}条记录，
                            共{this.state.productcount}条记录
                        </p>
                    }
                    <Pagination current={this.state.pageindex} total={this.state.productcount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                </div>
            </Modal>
        )
    }
}